/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

const _ = require('lodash')

// 引入 path 模块，用于处理文件和目录路径
const path = require('path')
// 获取项目根目录
const ROOT_DIR = path.join(__dirname, '..')
// helpers 目录
const HELPERS_DIR = path.join(ROOT_DIR, 'helpers')

// 计算预测数据
const { getKillGroupAccuracy } = require(path.join(HELPERS_DIR, 'getKillGroupAccuracy.js'))
// 过滤杀前组数组
const { filterForecaArray } = require(path.join(HELPERS_DIR, 'filterForecaArray.js'))
// 获取幸运和杀前组 id
const { getLuckAndForecastIds } = require(path.join(HELPERS_DIR, 'getLuckAndForecastIds.js'))

// 批量插入数据
const updateData = async (connection, calcData, update_table_name, isDataExempt = false) => {
  const updateValues = calcData.map((item) => [
    item.history_result_id,
    item.time,
    item.number,
    item.group_name,
    item.group_type,
    item.sub_index,
    item.accuracy
  ])

  try {
    await connection.query(
      `
        UPDATE ${update_table_name}
        SET
          red_continuous_limit_2_group_ids = ?,
          green_rebound_red_non_continuous_group_ids = ?,
          green_continuous_group_ids = ?,
          lucky_array = ?,
          kill_array = ?,
          accuracy = ?
        WHERE id = ?;
      `,
      [updateValues]
    )
    console.log(`批量插入完成：${calcData.length} 条`)
  } catch (err) {
    console.error('批量插入时出错:', err)
    throw err // 抛出错误以便事务回滚
  }
}

const filterItemsArrary = (item) => {
  const accuracyArray = item.accuracy_array

  if (accuracyArray.length >= 3) {
    const [secondLast, last] = accuracyArray.slice(-2)

    // 简化判断逻辑，返回条件直接判断
    return (secondLast === 0 && last !== 1) || (secondLast === 1 && last === 0)
  }

  return false
}

const updateHistoryForecast = async (pool, history_results, read_table_name, update_table_name) => {
  let previousElement = null

  // 获取连接池的连接
  const connection = await pool.getConnection()

  // 开始事务
  await connection.beginTransaction()

  try {
    const updateDataArray = []

    for (const [index, element] of history_results.entries()) {
      if (index < 2) {
        const temp = {
          ...element,
          red_continuous_limit_2_group_ids: null, // 预测红色连续不超过2次的group id数组
          green_rebound_red_non_continuous_group_ids: null, // 预测绿色回弹，红色不连续的group id数组
          green_continuous_group_ids: null, // 预测绿色连续的group id数组
          lucky_array: null,
          kill_array: null,
          accuracy: 1
        }
        // 前两条数据，不进行计算
        updateDataArray.push(temp)
      } else {
        const [prevSummary] = await connection.query(`SELECT * FROM ${read_table_name} WHERE history_result_id = ?`, [
          previousElement.id
        ])


        const accuracy = getKillGroupAccuracy(prevSummary, element.number)
        const [currentSummary] = await connection.query(`SELECT * FROM ${read_table_name} WHERE history_result_id = ?`, [
          element.id
        ])

        const { redContinuousLimit2Group, greenReboundRedNonContinuousGroup, greenContinuousGroup } = filterForecaArray(currentSummary)
        const {
          kill_array,
          lucky_array,
          red_continuous_limit_2_group_ids,
          green_rebound_red_non_continuous_group_ids,
          green_continuous_group_ids
        } = getLuckAndForecastIds(redContinuousLimit2Group, greenReboundRedNonContinuousGroup, greenContinuousGroup)

        // console.log('kill_array', kill_array)
        // console.log('lucky_array', lucky_array)
        // console.log('red_continuous_limit_2_group_ids', red_continuous_limit_2_group_ids)
        // console.log('green_rebound_red_non_continuous_group_ids', green_rebound_red_non_continuous_group_ids)
        // console.log('green_continuous_group_ids', green_continuous_group_ids)

        // 计算出 red_continuous_limit_2_group_ids
        // 计算出 green_rebound_red_non_continuous_group_ids
        // 计算出 green_continuous_group_ids
        // 计算出 lucky_array
        // 计算出 kill_array
        // 计算出 accuracy


        // todo
        updateDataArray.push({
          ...element, // filter
          // calc current
          red_continuous_limit_2_group_ids, // 预测红色连续不超过2次的group id数组
          green_rebound_red_non_continuous_group_ids, // 预测绿色回弹，红色不连续的group id数组
          green_continuous_group_ids, // 预测绿色连续的group id数组
          lucky_array,
          kill_array,
          accuracy
        })
      }
      // 成功输出
      // console.log(`${element.id} 插入完成`)
      // 更新 previousElement 为当前元素
      previousElement = element
    }

    // await updateData(connection, updateDataArray, update_table_name)

    // 提交事务
    await connection.commit()
  } catch (err) {
    // 回滚事务
    await connection.rollback()
    console.error('处理过程中发生错误:', err)
  } finally {
    // 释放连接
    connection.release()
  }
}

module.exports = { updateHistoryForecast }
